/**
 * 定义系统常用的字典，缓存起来，避免多次发起请求
 */
import http from './http.js';
let BUSINESS_DICT = {}

// 获取字典数据  categoryArray字典数组，callback请求成功回调方法
const getDicts = (categoryArray, callback) => {
  let params = [];   // 请求参数
  let result = {};   // 需要的字典数据
  
  for (let i = 0; i < categoryArray.length; i++) {   // 判断之前是否已经请求过字典，是否已经有存在的字典，去重
    if (BUSINESS_DICT[categoryArray[i]] == null || BUSINESS_DICT[categoryArray[i]].length == 0) {
      params.push(categoryArray[i]);   //去重后返回所需请求参数
    } else {
      result[categoryArray[i]] = BUSINESS_DICT[categoryArray[i]];
    }
  }
  if (params.length > 0) {
    //发起http请求，从后台获取数据
    http.request({
      url: "/dict/findDictCategoryList",
      data: {
        categorys: params.join(',')
      },
      success: res => {
        console.log(res)
        for (let i = 0; i < categoryArray.length; i++) {
          // console.log(res)
          BUSINESS_DICT[res[i].category] = res[i].dictList;
          result[res[i].category] = res[i].dictList;
        }
        callback(result)
      },
    })
  } else {
    callback(result)
  }
  // 返回promise
  // let params = [];
  // let result = {};
  // for (let i = 0; i < categoryArray.length; i++) {
  //   if (BUSINESS_DICT[categoryArray[i]] == null || BUSINESS_DICT[categoryArray[i]].length == 0) {
  //     params.push(categoryArray[i]);
  //   } else {
  //     result[categoryArray[i]] = BUSINESS_DICT[categoryArray[i]];
  //   }
  // }
  // if (params.length > 0) {
  //   //发起http请求，从后台获取数据
  //   return new Promise(resolve => {
  //     http.request({
  //       url: "/dict/findDictCategoryList",
  //       data: {
  //         categorys: categoryArray.join(',')
  //       },
  //       success: res => {
  //         wx.hideLoading();
  //         for (let i = 0; i < categoryArray.length; i++) {
  //           BUSINESS_DICT[res[i].category] = res[i].dictList;
  //           result[res[i].category] = res[i].dictList;
  //         } 
  //         resolve(result)
  //       },
  //     })
  //   })
  // } else {
  //   return new Promise(resolve => {
  //     resolve(result)
  //   })
  // }
}

const deleteDicts = () => {
  BUSINESS_DICT = {};
}
module.exports = {
  getDicts: getDicts,
  deleteDicts: deleteDicts
}